<template>
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
            <el-form-item label="商品名称:" prop="name">
                <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
                </el-button>
            </el-col>
            <!-- <el-col :span="1.5">
          <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
          >修改
          </el-button>
        </el-col> -->
            <!-- <el-col :span="1.5">
          <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
          >删除
          </el-button>
        </el-col> -->
        </el-row>

        <!--------------------------------------------- 主页面 --------------------------------------------->
        <div style="height: 70vh; overflow-y: auto; top:10%; width: 100%;">
            <el-table v-loading="loading" :data="productList">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column label="序号" align="center" prop="id" width="100" /> -->
                <el-table-column label="商品名称" align="center" prop="name" :show-overflow-tooltip="true" width="280" />

                <el-table-column label="商品价格" align="center" prop="price" width="120" />
                <el-table-column label="商品图片" align="center" prop="image" width="300">
                    <template slot-scope="scope">
                        <img :src="scope.row.image" alt="" style="width: 80px; height: 80px" />
                    </template>
                </el-table-column>
                <el-table-column label="商品详情" align="center" prop="detail" width="200" />

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row.id)">修改
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-s-goods" @click="handleShelves(scope.row.id)">开启秒杀
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品价格" prop="price">
                            <el-input v-model="form.price" placeholder="请输入商品价格" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="商品库存" prop="stock">
                            <el-input v-model="form.stock" placeholder="请输入商品价格" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="商品详情" prop="detail">
                            <el-input v-model="form.detail" placeholder="请输入商品详情" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="商品图片" prop="image">
                            <el-input v-model="form.image" placeholder="请输入商品图片url" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 开启秒杀对话框 -->
        <el-dialog :title="miaoshaTitle" :visible.sync="miaoshaOpen" width="780px" append-to-body>
            <el-form ref="miaoshaForm" :model="miaoshaForm" :rules="miaoshaRules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="商品数量" prop="stock">
                            <el-input v-model="miaoshaForm.stock" placeholder="请输入商品秒杀数量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="秒杀价格" prop="price">
                            <el-input v-model="miaoshaForm.price" placeholder="请输入商品秒杀价格" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="开始时间" prop="startTime">
                            <el-date-picker v-model="miaoshaForm.startTime" type="datetime"
                                placeholder="请选择开始时间"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="结束时间" prop="endTime">
                            <el-date-picker v-model="miaoshaForm.endTime" type="datetime"
                                placeholder="请选择结束时间"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm2">确 定</el-button>
                <el-button @click="cancel2">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import {
    listProduct,
    getProduct,
    delProduct,
    addProduct,
    updateProduct,
    shelvesProduct,
} from "@/api/product";
import { addMiaosha } from "@/api/goods";
import { MessageBox } from "element-ui";

export default {
    name: "Product",
    data() {
        return {
            // 遮罩层
            loading: true,
            goodsId: null,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商品表格数据
            productList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            miaoshaTitle: "",
            miaoshaOpen: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                productName: "",
            },
            // 表单参数
            form: {},
            miaoshaForm: {},
            // 表单校验
            rules: {
                name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
                price: [{ required: true, message: "商品价格不能为空", trigger: "change" }],
                stock: [{ required: true, message: "商品库存不能为空", trigger: "change" }],
                image: [{ required: true, message: "商品图片不能为空", trigger: "change" }],
                detail: [{ required: true, message: "商品详情不能为空", trigger: "change" }],
            },
            miaoshaRules: {
                stock: [{ required: true, message: "商品库存不能为空", trigger: "change" }],
                price: [{ required: true, message: "商品价格不能为空", trigger: "change" }],
                startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
                endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
            },
        };
    },
    mounted() {
        this.getList();
    },
    methods: {
        /** 查询商品列表 */
        getList() {
            this.loading = true;
            console.log(this.queryParams);
            listProduct(this.queryParams).then((response) => {
                this.productList = response.data;
                this.loading = false;
            }).catch((err) => {

            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
        },
        // 秒杀取消按钮
        cancel2() {
            this.miaoshaOpen = false;
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                name: undefined,
                price: undefined,
                detail: undefined,
                image: undefined,
            };
            this.resetForm("form");
        },
        // 秒杀表单重置
        resetMiaoshaForm() {
            this.miaoshaForm = {
                price: undefined,
                stock: undefined,
                startTime: undefined,
                endTime: undefined,
            };
            this.resetForm("miaoshaForm");
        },
        // 重置指定表单
        resetForm(refName) {
            console.log(refName);
            if (this.$refs[refName]) {
                console.log("reset!!!!");
                this.$refs[refName].resetFields();
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.productName = ""
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加商品";
        },
        /** 修改按钮操作 */
        handleUpdate(id) {
            this.reset();
            getProduct(id).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "修改商品";
            });
        },
        /** 秒杀按钮操作 */
        handleShelves(id) {
            this.resetMiaoshaForm();
            this.miaoshaOpen = true;
            this.miaoshaTitle = "上架秒杀商品";
            this.miaoshaForm.goodsId = id;
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateProduct(this.form).then((response) => {
                            MessageBox.alert("修改成功", "成功", {
                                confirmButtonText: "确定",
                                type: "success",
                            });
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addProduct(this.form).then((response) => {
                            MessageBox.alert("新增成功", "成功", {
                                confirmButtonText: "确定",
                                type: "success",
                            });
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 提交按钮 */
        submitForm2: function () {
            this.$refs["miaoshaForm"].validate((valid) => {
                if (valid) {
                    this.miaoshaForm.startTime = this.formatDateTime(this.miaoshaForm.startTime);
                    this.miaoshaForm.endTime = this.formatDateTime(this.miaoshaForm.endTime);
                    addMiaosha(this.miaoshaForm).then((response) => {
                        MessageBox.alert("开启秒杀成功", "成功", {
                            confirmButtonText: "确定",
                            type: "success",
                        });
                        this.miaoshaOpen = false;
                        this.getList();
                    });
                }
            });
        },
        formatDateTime(datetime) {
            const date = new Date(datetime);
            const year = date.getFullYear();
            const month = this.padZero(date.getMonth() + 1);
            const day = this.padZero(date.getDate());
            const hours = this.padZero(date.getHours());
            const minutes = this.padZero(date.getMinutes());
            const seconds = this.padZero(date.getSeconds());

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        padZero(value) {
            return String(value).padStart(2, "0");
        },
        /** 删除按钮操作 */
        handleDelete(id) {
            MessageBox.confirm("确认要删除吗？", "删除", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delProduct(id);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {
                    // 用户点击了取消按钮或者关闭了弹框
                });
        },

        /** 下架*/
        handleRemoved(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认下架编号为"' + ids + '"的数据项？')
                .then(function () {
                    return removeProduct(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("下架成功");
                })
                .catch(() => { });
        },
    },
};
</script>
  
<style scoped lang="scss">
.version-content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    ::v-deep {
        * {
            display: inline;
        }

        p {
            margin: 0;
        }
    }
}

.el-form-item {
    margin-bottom: 20px !important;
}

.version-content-title {
    ::v-deep {
        p {
            margin: 1em;
            line-height: 1.5;
        }
    }
}
</style>
<style>
.el-main {
    line-height: normal;
}
</style>
  